package controller

import (
	"encoding/json"
	"fmt"
	"go-gateway-learn/dao"
	"go-gateway-learn/dto"
	"go-gateway-learn/middleware"
	"go-gateway-learn/public"

	"go-gateway-learn/golang_common/lib"

	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
)

type AdminController struct {
}

func AdminRegister(routerGroup *gin.RouterGroup) {
	adminInfo := &AdminController{}
	routerGroup.GET("/info", adminInfo.AdminInfo)
	routerGroup.POST("/changepwd", adminInfo.ChangePwd)
}

// AdminInfo godoc
// @Summary 管理员信息获取
// @Description 管理员信息获取
// @Tags 管理员接口
// @ID /admin/info
// @Accept  json
// @Produce  json
// @Success 200 {object} middleware.Response{data=dto.AdminInfoOutput} "success"
// @Router /admin/info [GET]
func (adminInfo *AdminController) AdminInfo(c *gin.Context) {
	sess := sessions.Default(c)
	sessionInfo := sess.Get(public.AdminSessionInfoKey)
	adminSessionInfo := &dto.AdminSessionInfo{}
	if err := json.Unmarshal([]byte(fmt.Sprint(sessionInfo)), adminSessionInfo); err != nil {
		middleware.ResponseError(c, 2000, err)
		return
	}

	out := &dto.AdminInfoOutput{
		ID:           adminSessionInfo.ID,
		UserName:     adminSessionInfo.UserName,
		LoginTime:    adminSessionInfo.LoginTime,
		Avatar:       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
		Introduction: "I amd a super administrator",
		Roles:        []string{"admin"},
	}
	middleware.ResponseSuccess(c, out)
}

// ChangPwd godoc
// @Summary 官理员密码修改
// @Description 管理员密码修改
// @Tags 管理员接口
// @ID /admin/changpwd
// @Accept  json
// @Produce  json
// @Param Adminbody body dto.ChangePwdInput true "body"
// @Success 200 {object} middleware.Response{data=string} "success"
// @Router /admin/changpwd [POST]
func (adminInfo *AdminController) ChangePwd(c *gin.Context) {
	param := &dto.ChangePwdInput{}
	if err := param.BindValid(c); err != nil {
		middleware.ResponseError(c, 2000, err)
		return
	}
	sess := sessions.Default(c)
	sessionInfo := sess.Get(public.AdminSessionInfoKey)
	adminSessionInfo := &dto.AdminSessionInfo{}
	if err := json.Unmarshal([]byte(fmt.Sprint(sessionInfo)), adminSessionInfo); err != nil {
		middleware.ResponseError(c, 2001, err)
		return
	}

	db, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 2002, err)
		return
	}
	admin := &dao.Admin{}
	admin, err = admin.Find(c, db, (&dao.Admin{UserName: adminSessionInfo.UserName}))
	if err != nil {
		middleware.ResponseError(c, 2003, err)
		return
	}
	saltPassword := public.GenSaltPassword(admin.Salt, param.Password)
	admin.Password = saltPassword
	if err := admin.Save(c, db); err != nil {
		middleware.ResponseError(c, 2004, err)
		return
	}
	middleware.ResponseSuccess(c, "")
}
